import qs from 'qs'
import { defineAsyncComponent, markRaw } from 'vue'
import { deepClone } from '@/utils/index'
import BasicLayout from '@yang/layouts/index'
/**
 * 根据path路径获取matched
 * @param routes 菜单routes
 * @param path 路径
 * @returns {*} matched
 */
export function handleMatched(routes: any, path: string) {
  const arr = routes.filter((route: any) => (route?.childrenPathList || []).includes(path))
  const test = arr.flatMap((route: any) => {
    return route.children ? [route, ...handleMatched(route.children, path)] : [route]
  })
  return test
}

function getChilderPath(arr: any, path: string) {
  const paths = deepClone(arr).map((el: any) => {
    let nextPaht: any = ''
    if (el.path.includes('/')) {
      nextPaht = el.path
    } else {
      nextPaht = path === '/' ? `${path}${el.path}` : `${path}/${el.path}`
    }
    if (el?.children && el.children.length > 0) {
      return getChilderPath(el.children, nextPaht)
    } else {
      return {
        paths: [nextPaht],
        names: [el.name]
      }
    }
  })
  return {
    paths: JSON.parse(JSON.stringify(paths))
      .map((el: any) => {
        return el.paths
      })
      .flat(),
    names: JSON.parse(JSON.stringify(paths))
      .map((el: any) => {
        return el.names
      })
      .flat()
  }
}
/**
 * 将权限路由转换成vue路由
 * @param routes - 权限路由
 * @description 所有多级路由都会被转换成二级路由
 */
export function transformAuthRouteToVueRoutes(routes: any, path?: string) {
  return routes.map((el: any) => {
    let nextPaht: any = ''
    if (el.path.includes('/')) {
      nextPaht = el.path
    } else {
      nextPaht = path === '/' ? `${path}${el.path}` : `${path}/${el.path}`
    }
    if (el.component === 'Layout') {
      el.component = BasicLayout
    } else {
      const modules = import.meta.glob([
        '../views/*.tsx',
        '../views/*/*.tsx',
        '../views/*/*/*.tsx',
        '../views/*/*/*/*.tsx'
      ])
      const link: any = modules[`../${el.component}.tsx`]
      el.component = markRaw(defineAsyncComponent(link))
    }
    if (el.children && el.children.length > 0) {
      el.children = transformAuthRouteToVueRoutes(el.children, nextPaht)
      const childerInfo = getChilderPath(el.children, el.path)
      el.childrenPathList = childerInfo.paths
      el.childrenNameList = childerInfo.names
    } else {
      el.childrenPathList = [nextPaht]
      el.childrenNameList = [el.name]
    }
    return el
  })
}

/**
 * 根据当前route获取激活菜单
 * @param route 当前路由
 * @param isTab 是否是标签
 * @returns {string|*}
 */
export function handleActivePath(route: any, isTab = false) {
  const { meta, path } = route
  const rawPath = route.matched ? route.matched[route.matched.length - 1].path : path
  const fullPath =
    route.query && Object.keys(route.query).length
      ? `${route.path}?${qs.stringify(route.query)}`
      : route.path
  if (isTab) return meta.dynamicNewTab ? fullPath : rawPath
  if (meta.activeMenu) return meta.activeMenu
  return fullPath
}
